<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
	pageContext.setAttribute("APP_PATH", request.getContextPath());
	//String userName =(String) request.getAttribute("userName"); 
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>员工列表</title>
<link rel="stylesheet" type="text/css"
	href="${APP_PATH}/static/bootstrap/css/bootstrap.css" />
<script type="text/javascript"
	src="${APP_PATH}/static/jquery/jquery-3.4.1.js"></script>
<script type="text/javascript"
	src="${APP_PATH}/static/bootstrap/js/bootstrap.js"></script>
<link rel="stylesheet"
	href="http://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<link rel="stylesheet"
	href="https://jqueryui.com/resources/demos/style.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
	$(function() {
		jump_to(1);
		$("#addBtn").click(
				function() {
					//清空表单
					document.getElementById("empForm").reset();
					$("#name").parent().removeClass("has-error has-success");
					$("#name").next("span").empty();
					$("#email").next("span").empty();
					$("#email").parent().removeClass("has-error has-success");

					//查询所有部门
					$.ajax({
						url : "${APP_PATH}/dept/findAllDepts",
						type : "POST",
						success : function(result) {
							//清理之前的部门数据
							$("#addEmpModal select").empty();
							$.each(result.data.deptList, function(index, dept) {
								var opt = $("<option></option>").append(
										dept.name).attr("value", dept.id);
								$("#addEmpModal select").append(opt);
							});
							//[{"id":1,"name":"测试部"},{"id":2,"name":"测试部"}]
						}
					});

					//弹出（新增）模态窗口
					$('#addEmpModal').modal({
						backdrop : "static"
					});
				});

		//进行表单验证
		//1.对姓名进行正则表达式校验
		function checkNameForReg() {
			//1.姓名验证：姓名必须由2~10位大小写英文字母、空格、中文组成
			var regName = /^[a-zA-Z \u4E00-\u9FA5]{2,10}$/;
			var nameVal = $("#name").val();
			if (!regName.test(nameVal)) {
				$("#name").next("span").text("姓名必须由2~10位大小写英文字母、空格、中文组成");
				$("#name").parent().addClass("has-error");
				return false;
			} else {
				$("#name").next("span").empty();
				$("#name").parent().removeClass("has-error has-success");
				$("#name").parent().addClass("has-success");
				return true;
			}
		}

		//2.对邮箱进行正则表达式校验
		function checkEmailForReg() {
			var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
			var emailVal = $("#email").val();
			if (!regEmail.test(emailVal)) {
				$("#email").next("span").text("邮箱不符合格式");
				$("#email").parent().addClass("has-error");
				return false;
			} else {
				$("#email").next("span").empty();
				$("#email").parent().removeClass("has-error has-success");
				return true;
			}
		}

		//检验结果
		var checkResult_name = false;
		var checkResult_email = false;

		//姓名文本失去焦点，将姓名值异步放松到服务器进行重名性校验
		$("#name").blur(function() {
			//1.对姓名进行正则表达式校验
			if (checkNameForReg()) {
				//2.姓名进行重名校验
				$.ajax({
					url : "${APP_PATH}/emp/countTotal",
					type : "POST",
					data : {
						"name" : $(this).val()
					},
					success : function(result) {
						if (result.data.iRet == 0) {
							$("#name").next("span").text("可以使用该用户名");
							$("#name").parent().addClass("has-success");
							checkResult_name = true;
						} else {
							$("#name").parent().addClass("has-error");
							$("#name").next("span").text("该姓名已存在");
							checkResult_name = false;
						}
					}
				});
			} else {
				checkResult_name = false;
			}
		});

		//当邮箱文本框失去焦点时，对其进行正则检验
		$("#email").blur(function() {
			if (checkEmailForReg()) {
				checkResult_email = true;
			} else {
				checkResult_email = false;
			}
		});
		//新增员工表单提交(点击保存)
		$("#saveEmpBtn").click(function() {
			//向服务器发送保存请求(异步请求)
			if (checkResult_name && checkResult_email) {
				$.ajax({
					url : "${APP_PATH}/emp/saveEmpt",
					type : "POST",
					data : $("#addEmpModal form").serialize(),

					success : function(result) {
						if (result.code == 200) {
							//关闭新增模态窗口
							$("#addEmpModal").modal("hide");
							//跳转到最后一页
							jump_to(result.data.totalPages);
						}

					}
				});
			}
		});

		//更新操作
		$("#updateEmpBtn").click(function() {
			//1.数据有效性检验
			//2.对邮箱进行正则表达式校验

			//2.将表单提交给服务器进行更新操作、序列化表单值

			//$("#editEmpModal form").serialize();	
			$.ajax({
				url : "${APP_PATH}/emp/emp",
				type : "put",
				data : $("#editEmpModal form").serialize(),
				success : function(result) {
					//关闭更新窗口
					if (result.code == 300) {
						console.log(result.data);
						alert(result.data.errors.email);
					} else {
						$("#editEmpModal").modal("hide");
						//重新请求原来那一页
						jump_to($("#currentPageNo").val());

					}

				}
			});

		});

		$("#file").click(function() {
			//弹出模态窗口
			$('#uploadFileModal').modal({
				backdrop : "static"
			});
		});
		$("#uploadFile").click(function() {
			var file = $("#upload").val();

			file = file.substring(file.lastIndexOf('.'), file.length);
			if (file == '') {
				alert("上传文件不能为空！");
			} else if (file != '.xlsx' && file != '.xls') {
				alert("请选择正确的excel类型文件！");
			} else {
				ajaxFileUpload();
			}
		});
		function ajaxFileUpload() {
			var formData = new FormData();
			var name = $("#upload").val();
			formData.append("file", $("#upload")[0].files[0]);
			formData.append("name", name);
			$.ajax({
				url : "emp/excel/InputExcel.do",
				type : "POST",
				async : false,
				data : formData,
				processData : false,
				contentType : false,
				beforeSend : function() {
					console.log("正在进行，请稍候");
				},
				success : function(e) {
					if (e == "01") {
						alert("导入成功");
						$("#uploadFileModal").modal("hide");
					} else if (e == 'error') {
						alert("姓名重复");
					} else {
						alert("导入失败");
					}
				}
			});
		}

		/*  
		 *自动补全、模糊搜索
		 */
		//1. 准备数据。使用ajax 异步请求后台获得数据
		$.ajax({
			url : "${APP_PATH}/emp/complement",
			type : "GET",
			success : function(result) {
				if (result.code == '200') {
					console.log(result.data.empNameList.name);//控制台打印
					var text = result.data.empNameList;
					$("#searchText").autocomplete({
						source : text
					});
				}
			}
		});
	});
	//页面加载后
	//跳转到指定页面
	function jump_to(num) {
		$.ajax({
			url : "${APP_PATH}/emp/findAllEmployee",
			data : {
				"pn" : num
			},
			type : "POST",
			success : function(result) {
				layoutPage(result.data.pageInfo);
			}
		});
	}

	//将json数据布置到当前页面
	function layoutPage(result) {
		//清理员工数据
		$("#tb tr").first().nextAll().remove();
		//删除每次新追加的底部导航栏
		$("#nav_ul").empty();

		//构建列表数据
		buildEmpsTable(result);
		//构建分页信息
		buildPageInfo(result);
		//初始化分页导航
		buildPageNavigate(result);
	}

	//修改员工
	function updateEmp(id) {

		//将id设置到隐藏empid上
		$("#editEmpModal input[name=id]").val(id);

		//1.弹出（新增）模态窗口
		$('#editEmpModal').modal({
			backdrop : "static"
		});

		//2.初始化部门数据
		//查询所有部门信息

		$.ajax({
			url : "${APP_PATH}/dept/findAllDepts",
			type : "POST",
			success : function(result) {
				//清理之前的部门数据
				$("#editEmpModal select").empty();
				$.each(result.data.deptList, function(index, dept) {
					var opt = $("<option></option>").append(dept.name).attr(
							"value", dept.id);
					$("#editEmpModal select").append(opt);
				});
			}
		});

		//3.回填当前员工信息，根据id查找当前用户对象
		$.ajax({
					url : "${APP_PATH}/emp/emp/" + id,
					type : "get",
					success : function(result) {
						$("#editEmpModal p:first").text(result.data.emp.name);
						$("#editEmpModal input[name=gender]").val(
								[ result.data.emp.gender ]);
						$("#editEmpModal input[name=email]").val(
								result.data.emp.email);
						$("#editEmpModal select").val(
								[ result.data.emp.dept.id ]);
					}
				});
	}

	//构建列表数据
	function buildEmpsTable(result) {
		$.each(result.list, function(index, emp) {
			//生成一行员工记录
			var box_td = $("<td></td>").append(
					"<input type='checkbox'  value="+emp.id+">");
			var id_td = $("<td></td>").append(emp.id);
			var name_td = $("<td></td>").append(emp.name);
			var gender_td = $("<td></td>").append(emp.gender);
			var email_td = $("<td></td>").append(emp.email);
			var deptName_td = $("<td></td>").append(emp.dept.name);

			var span1 = $("<span aria-hidden='true'></span>").addClass(
					"glyphicon glyphicon-trash");
			var btnDelete = $(
					"<button onclick='deleteEmp(" + emp.id + ")'></button>")
					.addClass("btn btn-danger btn-sm").append(span1).append(
							" 删除");

			var span2 = $("<span aria-hidden='true'></span>").addClass(
					"glyphicon glyphicon-pencil");
			var btnUpdate = $(
					"<button onclick='updateEmp(" + emp.id + ")'></button>")
					.addClass("btn btn-success btn-sm").append(span2).append(
							" 修改");
			var operate_td = $("<td></td>").append(btnUpdate).append("&nbsp;")
					.append(btnDelete);

			//将以上6列容纳加入到一个新的<tr>内
			$("<tr></tr>").append(box_td).append(id_td).append(name_td).append(
					gender_td).append(email_td).append(deptName_td).append(
					operate_td).appendTo("#tb");
		});
	}

	//构建分页信息
	function buildPageInfo(result) {
		//初始化分页信息
		$("#pageInfo").text(
				"当前第" + result.pageNum + "页，总共" + result.pages + "页，总记录数"
						+ result.total + "条")
		$("#currentPageNo").val(result.pageNum);
	}

	//构建分页导航
	function buildPageNavigate(result) {
		//初始化分页导航
		//1.首页
		var topPage = $("<li onclick='jump_to(1)'></li>").append(
				"<a href='#'>首页</a>");
		$("#nav_ul").append(topPage);
		//上一页
		var span1 = $("<span aria-hidden='true'>&laquo;</span>")
		var pregeA = $("<a href='#' aria-label='Previous'></<a>").append(span1)
		//alert(result.prePage);
		var prePage = $(
				"<li onclick='jump_before(" + result.prePage + ",this)'></li>")
				.append(pregeA)

		$("#nav_ul").append(prePage);
		//如果当前页是第一页，禁用上一页
		if (result.pageNum == 1) {
			prePage.addClass("disabled");
		}

		//导航页
		$.each(result.navigatepageNums, function(index, num) {
			var A = $("<a></a>").append(num);
			var pageLi = $("<li onclick='jump_to(" + num + ")'></li>")
					.append(A);
			//高亮显示当前页
			if (result.pageNum == num) {
				pageLi.addClass("active");
			}
			$("#nav_ul").append(pageLi);
		});

		//下一页
		var span2 = $("<span aria-hidden='true'>&raquo;</span>")
		var nextA = $("<a href='#' aria-label='Next'></<a>").append(span2)

		var nextPage = $(
				"<li onclick='jump_before(" + result.nextPage + ",this)'></li>")
				.append(nextA)
		$("#nav_ul").append(nextPage);

		//如果当前页是尾页，禁用下一页
		if (result.pageNum == result.pages) {
			nextPage.addClass("disabled");
		}
		//尾页
		var bootomPage = $("<li onclick='jump_to(" + result.pages + ")'></li>")
				.append("<a href='#'>尾页</a>");
		$("#nav_ul").append(bootomPage);
	}

	function jump_before(num, li) {
		if ($(li).hasClass("disabled")) {
			return false;
		} else {//否则，正常跳转
			jump_to(num)
		}
	}

	function deleteAll() {
		// 获取input标签下type类型为checkbox的所有选中的checked框  
		var checkId = [];
		if (confirm('是否删除')) {
			if ($("input[type='checkbox']:checked").length > 0) {
				$("input[type='checkbox']:checked").each(function(i) {
					checkId[i] = $(this).val();
				});
			}
			alert(checkId);
			$.ajax({//利用ajax发出请求
				type : "POST",//post类型
				url : "${APP_PATH}/emp/deleteMany?id=" + checkId, //向Controller里的deleteSelect传输ids
				success : function(result) {//删除成功后，deleteMany会返回一个"ok";
					if (result.code == 200) {
						alert("删除成功！");//返回ok后弹出一个对话框。
						jump_to($("#currentPageNo").val());//相当于刷新界面
					}
				}
			});
		}
	}

	//单个删除员工
	function deleteEmp(id) {
		if (confirm("确认删除?")) {
			$.ajax({
				url : "${APP_PATH}/emp/emp/" + id,
				type : "delete",
				success : function() {
					//跳回原来界面
					jump_to($("#currentPageNo").val());
				}
			});
		}
	}

	//搜索Name
	function searchBtn() {
		var searchText = $("#searchText").val();
		if (searchText != null && searchText != '') {
			$.ajax({
				url : "${APP_PATH}/emp/search",
				data : {
					searchText : searchText
				},
				success : function(result) {
					if(result.code=='200'){
						$("input[id='searchText']").val("");
						$("#pageInfo").remove();
						$("#tb tr").first().nextAll().remove();
						//删除每次新追加的底部导航栏
						$("#nav_ul").empty();
						$.each(result.data.list, function(index, emp) {
							//生成一行员工记录
							var box_td = $("<td></td>").append(
									"<input type='checkbox'  value="+emp.id+">");
							var id_td = $("<td></td>").append(emp.id);
							var name_td = $("<td></td>").append(emp.name);
							var gender_td = $("<td></td>").append(emp.gender);
							var email_td = $("<td></td>").append(emp.email);
							var deptName_td = $("<td></td>").append(emp.dept.name);
							var span1 = $("<span aria-hidden='true'></span>").addClass(
							"glyphicon glyphicon-trash");
							var btnDelete = $(
							"<button onclick='deleteEmp(" + emp.id + ")'></button>")
							.addClass("btn btn-danger btn-sm").append(span1).append(
									" 删除");

							var span2 = $("<span aria-hidden='true'></span>").addClass(
							"glyphicon glyphicon-pencil");
							var btnUpdate = $(
							"<button onclick='updateEmp(" + emp.id + ")'></button>")
							.addClass("btn btn-success btn-sm").append(span2).append(
									" 修改");
							var operate_td = $("<td></td>").append(btnUpdate).append("&nbsp;")
							.append(btnDelete);
							//将以上6列容纳加入到一个新的<tr>内
							$("<tr></tr>").append(box_td).append(id_td).append(name_td).append(
									gender_td).append(email_td).append(deptName_td).append(
									operate_td).appendTo("#tb");
						});
					}else{
						alert("查询不到，请再输入一次");
						$("input[id='searchText']").val("").focus();
						
					}
					
				}
				
				
			});
		} else {
			alert("请输入名称");
		}

	}
</script>
<script type="text/javascript">
	function OutputExce() {
		if (confirm('是否导出成Excel')) {
			window.location.href = "emp/excel/OutputExcel.do";
		}

	}
</script>
<script type="text/javascript">
	
</script>
</head>
<body>
	<input type="hidden" id="currentPageNo" name="currentPageNo" />
	<!-- 编辑员工模态窗口 -->
	<div id="editEmpModal" class="modal fade" tabindex="-1" role="dialog"
		aria-labelledby="gridSystemModalLabel">

		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="gridSystemModalLabel">修改员工</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal">
						<input type="hidden" name="id" />
						<div class="form-group">
							<label for="name" class="col-sm-2 control-label">姓名</label>
							<div class="col-sm-10">
								<p class="form-control-static"></p>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">性别</label>
							<div class="col-sm-10">
								<label class="radio-inline"> <input type="radio"
									name="gender" value="男" checked="checked"> 男
								</label> <label class="radio-inline"> <input type="radio"
									name="gender" value="女"> 女
								</label>
							</div>
						</div>
						<div for="email" class="form-group">
							<label for="email" class="col-sm-2 control-label">Email</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" name="email"
									placeholder="邮箱"> <span id="helpBlock2"
									class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">部门</label>
							<div class="col-sm-4">
								<select class="form-control" name="dept.id">
									<!-- 				    	<option value="1">研发部</option> -->
								</select>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="updateEmpBtn">更新</button>
				</div>
			</div>
		</div>
	</div>





	<!-- 新增员工模态窗口 -->
	<div id="addEmpModal" class="modal fade" tabindex="-1" role="dialog"
		aria-labelledby="gridSystemModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="gridSystemModalLabel">新增员工</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" id="empForm">
						<div class="form-group">
							<label for="name" class="col-sm-2 control-label">姓名</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" id="name" name="name"
									placeholder="姓名"> <span id="helpBlock2"
									class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">性别</label>
							<div class="col-sm-10">
								<label class="radio-inline"> <input type="radio"
									name="gender" id="male" value="男" checked="checked"> 男
								</label> <label class="radio-inline"> <input type="radio"
									name="gender" id="female" value="女"> 女
								</label>
							</div>
						</div>
						<div for="email" class="form-group">
							<label for="email" class="col-sm-2 control-label">Email</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" id="email" name="email"
									placeholder="邮箱"> <span id="helpBlock2"
									class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">部门</label>
							<div class="col-sm-4">
								<select class="form-control" name="dept.id">
									<!-- 				    	<option value="1">研发部</option> -->
								</select>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="saveEmpBtn">保存</button>
				</div>
			</div>
		</div>
	</div>

	<!--编辑文件上传模态框  -->

	<div id="uploadFileModal" class="modal fade" tabindex="-1"
		role="dialog" aria-labelledby="gridSystemModalLabel">
		<div class="modal-content">
			<div class="modal-header">
				<div class="col-sm-5">
					<input type="file" id="upload" name="upload" class="form-control"
						value=".." />
				</div>
				<div class="modal-footer">
					<input type="button" id="uploadFile" class="btn btn-primary"
						value="上传" />
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
				</div>
			</div>
		</div>
	</div>

	<!-- 主页  -->

	<div class="container">
		<div class="row">
			<div class="col-md-4">
			<div style="float: left;margin-top:25px">
				<font size="10">管理员</font>
				<button type="button" class="btn btn-default btn-sm">
					<span class="glyphicon glyphicon-user"></span> ${userName}
				</button>
				</div>

			</div>
			<div class="col-md-5" style="margin-top: 25px">
				<input type="text" id="searchText" />
				<button class="btn btn-success" onclick="searchBtn()">搜索</button>
				<button class="btn" id="addBtn">新增</button>
				<button class="btn btn-warning" id="deleteAll" onclick="deleteAll()">勾选删除</button>
			</div>
		</div>


		<div class="row">
			<div class="span6">
				<ul class="nav nav-tabs">
					<li class="active"><a href="toFlsh?userName=${userName}">Home</a>
					</li>
					<li class="dropdown"><a class="dropdown-toggle"
						data-toggle="dropdown" href="#">Excel<b class="caret"></b></a>
						<ul class="dropdown-menu">
							<li><a class="btn" id="file">上传</a></li>
							<li class="divider"></li>
							<li><a class="btn btn-success" onclick="OutputExce()">导出</a></li>
						</ul></li>
					<li><a id="tj" href="myEchart.jsp">统计</a></li>
					<li><a class="btn btn-danger" id="exitBtn" href="login.jsp">退出</a></li>
				</ul>
			</div>
		</div>



		<!-- 	<div class="row">

			<div style="height: 50px;margin-top: 10px" class="col-md-4">
				<button class="btn btn-success" id="addBtn">新增</button>
				<button class="btn" id="file">上传</button>
				<button class="btn btn-success" onclick="OutputExce()">导出</button>
				<a class="btn btn-success" id="tj" href="myEchart.jsp">统计</a>
				<button class="btn btn-success" id="deleteAll" onclick="deleteAll()">删除</button>
				<a class="btn btn-danger" id="exitBtn" href="login.jsp">退出</a>
			</div>

		</div> -->
		<div class="row" style="margin-top: 10px">
			<table class="table table-hover table-bordered" id="tb">
				<tr>
					<th><input type="checkbox" disabled /></th>
					<th>编号</th>
					<th>姓名</th>
					<th>性别</th>
					<th>Email</th>
					<th>部门</th>
					<th>操作</th>
				</tr>

				<%-- 				<tr>
					<td>${emp.id}</td>
					<td>${emp.name }</td>
					<td>${emp.gender}</td>
					<td>${emp.email}</td>
					<td>${emp.dept.name}</td>
					<td>
						<button class="btn btn-success btn-sm"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 修改</button>
						<button class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除</button>
					</td>
				</tr> --%>

			</table>
		</div>

		<div class="row">
			<div class="col-md-6" id="pageInfo"></div>
			<div class="col-md-6">
				<nav aria-label="Page navigation">
				<ul class="pagination" id="nav_ul">
					<!-- 					   <li><a href="">首页</a></li>
					   <li>
					      <a href="" aria-label="Previous">
					        <span aria-hidden="true">&laquo;</span>
					      </a>
			      	   </li>
			      	   				
					   <li><a href="">1</a></li>
					   <li><a href="">2</a></li>
			      	   
						<li>
			    		  <a href="" aria-label="Next">
					       	 <span aria-hidden="true">&raquo;</span>
					      </a>
						</li>
					   
					    <li><a href="">尾页</a></li> -->
				</ul>
				</nav>
			</div>
		</div>
	</div>
	<%@include file="/footer.jsp" %>
</body>
</html>
